<template>
  <el-dialog
    :model-value="dialogVisible"
    :title="dialogTitle"
    width="40%"
    :close="handleClose"
  >
    <el-form ref="formRef" :model="form" label-width="80px" :rules="rules">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="form.roleName" />
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="form.roleDesc" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, ref, defineProps, watch } from 'vue'
import { addRoles, editRoles } from '@/api/roles'
import { ElMessage } from 'element-plus'
// 使用自己定义的i18n
import i18n from '@/i18n'

// 导入父传子的内容
const props = defineProps({
  dialogTitle: {
    type: String,
    default: '',
    required: true
  },
  dialogTitleValue: {
    type: Object,
    default: () => {}
  }
})

// 表单内容
const formRef = ref(null)
const form = ref({
  roleName: '',
  roleId: '',
  roleDesc: '',
  mobile: ''
})
// 表单校验
const rules = ref({
  roleName: [{ required: true, message: '角色名错误', trigger: 'blur' }],
  roleDesc: [{ required: true, message: '角色描述错误', trigger: 'blur' }]
})

watch(
  () => props.dialogTitleValue,
  () => {
    // console.log(props.dialogTitleValue)
    form.value = props.dialogTitleValue
  },
  { deep: true, immediate: true }
)
// 因为可能会有很多方法，所以是数组,用法model-value要改成大小写
const emits = defineEmits(['update:modelValue', 'initUserList'])
// 然后点击事件发送false关闭弹窗
const handleClose = () => {
  emits('update:modelValue', false)
}

// 点击确认事件中调用addRoles传递，表单内容
const handleConfirm = () => {
  // 表单校验
  formRef.value.validate(async (valid) => {
    if (valid) {
      props.dialogTitle === '添加角色'
        ? await addRoles(form.value)
        : await editRoles(form.value)
      ElMessage({
        message: i18n.global.t('message.updeteSuccess'),
        type: 'success'
      })
      emits('initUserList')
      handleClose()
    } else {
      console.log('error submit!!')
      return false
    }
  })
}
</script>
<style lang="scss" scoped></style>
